package com.ey12.file;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetDatas extends HttpServlet {
	private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
	private static String URL = "";
	private static String USN = "";
	private static String PWD = "";

	/**
	 * Constructor of the object.
	 */
	public GetDatas() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);

	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		URL = this.getServletContext().getInitParameter("DbUrl");
		USN = this.getServletContext().getInitParameter("DbUsername");
		PWD = this.getServletContext().getInitParameter("DbPwd");
		request.setCharacterEncoding("UTF-8");
		String sign = request.getParameter("sign");
		String result = "";
		if (sign.equals("1")) {
			result = findOrders();
		} else if (sign.equals("2")) {
			result = findUsers();
		} else if (sign.equals("3")) {
			// String username=request.getParameter("username");
			String username = new String(request.getParameter("username")
					.getBytes("iso8859-1"), "utf-8");
			result = String.valueOf(getValid(username));
		} else if (sign.equals("4")) {
			String id = new String(request.getParameter("id").getBytes(
					"iso8859-1"), "utf-8");
			result = findOrderStateById(id);
		}
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
		response.setHeader("Pragma", "no-cache"); // HTTP 1.0
		response.setDateHeader("Expires", 0); // prevents caching at the proxy
		// server
		PrintWriter w = response.getWriter();
		w.write(result);
		w.flush();
		w.close();

	}

	public int getValid(String username) {
		int flag = 0;
		Connection conn = getConnectionByJDBC();
		String sqlx = "select is_valid from gm_user where user_name='"
				+ username + "'";
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			if (rs.next()) {
				flag = rs.getInt("is_valid");
			}
			rs.close();
			stmt.close();
			conn.close();

			System.out.println(sqlx + "------" + flag);
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return flag;
	}

	public String findgameName(int game_id, int cserver_id) {
		String game_name = "";
		Connection conn = getConnectionByJDBC();
		String sqlx = "select game_name from gm_game where id=" + game_id;
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			if (rs.next()) {
				game_name = rs.getString("game_name");
				String cserverName = findCserverName(cserver_id);
				game_name = game_name + "/" + cserverName;
			}
			rs.close();
			stmt.close();
			conn.close();

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return game_name;
	}

	public String findCserverName(int cserver_id) {
		String result = "";
		Connection conn = getConnectionByJDBC();
		String sqlx = "select cserver_name,sever_type,unit from gm_cserver where id="
				+ cserver_id;
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			if (rs.next()) {
				result = result + rs.getString("cserver_name") + "/";
				result = result + rs.getString("sever_type") + "/";
				result = result + rs.getString("unit");
				return result;
			}
			rs.close();
			stmt.close();
			conn.close();

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	public String findUsers() {
		StringBuffer buff = new StringBuffer();
		Connection conn = getConnectionByJDBC();
		String sqlx = "select user_name,point from gm_user where user_type=1 and is_valid=1 order by point desc limit 7";
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			System.out.println("findUsers=" + sqlx);
			buff.append("<catalog>");
			while (rs.next()) {
				buff.append("<user>");
				String user_name = rs.getString("user_name");
				String point = String.valueOf(rs.getInt("point"));
				buff.append("<userName>").append(user_name).append(
						"</userName>");
				buff.append("<point>").append(point).append("</point>");
				buff.append("</user>");
			}
			rs.close();
			stmt.close();
			conn.close();

			buff.append("</catalog>");
			// System.out.println("findUsers=" + buff.toString());

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return buff.toString();
	}

	public String findOrders() {
		StringBuffer buff = new StringBuffer();
		Connection conn = getConnectionByJDBC();
		String sqlx = "	select order_num,need_money,create_date,buy_num,game_id,cserver_id from gm_order order by id desc limit 9";
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			System.out.println("findOrders=" + sqlx);
			buff.append("<catalog>");
			while (rs.next()) {
				buff.append("<game>");
				String order_num = rs.getString("order_num");
				String need_money = String.valueOf(rs.getLong("need_money"));
				String create_date = rs.getString("create_date");
				String buy_num = String.valueOf(rs.getInt("buy_num"));
				int game_id = rs.getInt("game_id");
				int cserver_id = rs.getInt("cserver_id");

				String game_name = findgameName(game_id, cserver_id);
				buff.append("<orderNum>").append(order_num).append(
						"</orderNum>");
				buff.append("<gameName>").append(game_name).append(
						"</gameName>");
				buff.append("<buyNum>").append(buy_num).append("</buyNum>");
				buff.append("<money>").append(need_money).append("</money>");
				buff.append("<date>").append(create_date).append("</date>");
				buff.append("</game>");
			}
			buff.append("</catalog>");
			// System.out.println("findOrders=" + buff.toString());

			rs.close();
			stmt.close();
			conn.close();

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return buff.toString();
	}

	public String findOrderStateById(String id) {

		Connection conn = getConnectionByJDBC();
		String sqlx = "	select pay_state,rec_state,state from gm_order where id="
				+ id;
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sqlx);
			System.out.println("findOrderStateById=" + sqlx);

			if (rs.next()) {
				int pay_state = rs.getInt("pay_state");
				int rec_state = rs.getInt("rec_state");
				int state = rs.getInt("state");
				if (pay_state == 2) {
					rs.close();
					stmt.close();
					conn.close();

					return "fault";
				} else if (state == 2) {
					rs.close();
					stmt.close();
					conn.close();

					return "fault";
				} else {
					rs.close();
					stmt.close();
					conn.close();

					return "success";
				}

			}

			// System.out.println("findOrderStateById=" + buff.toString());

			rs.close();
			stmt.close();
			conn.close();

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return "fault";
	}
	
	public static Connection getConnectionByJDBC() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(URL, USN, PWD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
//	public static Connection getConnectionByJDBC() {
//		// Connection conn = null;
//		// try {
//		// Class.forName("com.mysql.jdbc.Driver");
//		// } catch (ClassNotFoundException e) {
//		// e.printStackTrace();
//		// }
//		// try {
//		// conn = DriverManager.getConnection(URL, USN, PWD);
//		// } catch (SQLException e) {
//		// e.printStackTrace();
//		// }
//		return DBPoolFactory.getConnectionByPool();
//	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
